/* *****************************************************************************
*
*	danizone.ch
*
*	Developer:		mda010
*	Creation date:	May 6, 2012 7:57:24 PM
*	
*	Project name:	HomegrownCuisine
*	File name:		AbstractEntity.java
*
*	Copyrights (C) 2012 @danizone.ch
*
*   This program is free software; you can redistribute it and/or modify
*	it under the terms of the GNU General Public License as published by
*	the Free Software Foundation; either version 2 of the License, or
*	(at your option) any later version.
*
*	This program is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*	GNU General Public License for more details.
*
*	Change history:	[developer]; [date];[reason for change]
*
*					mda010; May 6, 2012; created
*
***************************************************************************** */
package ch.zhaw.hgc.entities.base;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import com.google.appengine.api.datastore.Key;

/**
 * Implementation note goes here!
 */
@MappedSuperclass
@EntityListeners(AbstractEntity.AbstractEntityListener.class)
public abstract class AbstractEntity implements Serializable{

	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Key key;
	
	private Date dateCreated;	
	private Date dateModified;

	/**
	 * @return the key
	 */
	public Key getKey(){

		return key;
	}
		
	/**
	 * @return the dateCreated
	 */
	public Date getDateCreated(){
		
		if(dateCreated == null)
			dateCreated = new Date();
		
		return dateCreated;
	}

	/**
	 * @return the dateModified
	 */
	public Date getDateModified(){
		return dateModified;
	}
	
	public void setDateModified(Date date){		
		dateModified = date;
	}

	@Override
	public int hashCode(){

		return getKey().hashCode();
	}

	@Override
	public boolean equals(Object obj){
		
		return (obj == this || (obj instanceof AbstractEntity && getKey().equals(((AbstractEntity)obj).getKey())));
	}		
	
	public static class AbstractEntityListener{
		
		@PrePersist
		public void onPrePersist(AbstractEntity abstractEntity){
			
			abstractEntity.setDateModified(abstractEntity.getDateCreated());
		}
		
		@PreUpdate
		public void onPreUpdate(AbstractEntity abstractEntity){
			
			abstractEntity.setDateModified(new Date());
		}
	}	
}